package com.bzy.common.bean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bzy.common.exception.LogicException;
import com.bzy.common.exception.SpringValidException;
import com.bzy.common.exception.SqlException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class BaseController {
	
	private static boolean IS_DEBUG = true;

	@Autowired
	private MessageSource messageSource;
	
	public MessageSource getMessageSource() {
		return messageSource;
	}
	
	public String getMessage(String code, Object[] params) {
		return getMessageSource().getMessage(code, params, getRequest().getLocale());
	}
	
	private ThreadLocal<Result> resultThread = new ThreadLocal<Result>();
	
	Result getResult() {
		
		if (resultThread.get() == null) {
			resultThread.set(new Result());
		}
		return resultThread.get();
	}
	
	protected HttpServletRequest getRequest() {
    	return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }

    protected HttpServletResponse getResponse() {
    	return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    }
    
	
	@ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Result errorResponse(Exception exception) {
    	
//		LoggerUtil.error("BaseController.java--errorResponse");
		
    	Exception error = IS_DEBUG ? exception : null;
    	
    	if (exception instanceof BindException) {
    		BindException ex = (BindException)exception;
    		exception = new SpringValidException(ex.getBindingResult());
    	}
    	
    	if (exception instanceof LogicException) {
    		return new Result(false, exception.getMessage(), error);
    	}
    	
    	if (exception instanceof SqlException) {
    		return new Result(false, exception.getMessage(), error);
    	}
    	
    	if (exception instanceof SpringValidException) {
    		return new Result(false, getMessage("system.valid.error", null), ((SpringValidException)exception).getErrorMessages());
    	}
    	
    	return new Result(false,getMessage("system.error", null), error);
    }
}
